package cn.xw.commons.core.domain;

import cn.xw.commons.core.constant.HttpStatus;

import java.io.Serializable;

/**
 * 响应主体信息
 *
 * @param <T> 数据类型
 * @author Anhui AntLaddie <a href="https://www.cnblogs.com/antLaddie/">(博客园蚂蚁小哥)</a>
 * @version 1.0
 **/
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 成功状态码
     */
    public static final int SUCCESS = HttpStatus.HTTP_OK;

    /**
     * 失败状态码
     */
    public static final int FAIL = HttpStatus.HTTP_INTERNAL_ERROR;

    /**
     * 告知程序成功还是失败
     */
    private int code;

    /**
     * 告知程序成功还是失败字符串信息
     */
    private String msg;

    /**
     * 响应具体实例数据
     */
    private T data;

    /***
     * 构造器
     * @param data 响应数据
     * @param code 响应码
     * @param msg 响应信息
     * @return <T> AjaxResult<T>
     * @param <T> 数据类型
     */
    private static <T> Result<T> restResult(T data, int code, String msg) {
        Result<T> apiResult = new Result<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    // ================= 构建对象语法糖 ok成功响应、fail失败响应 ================== //

    public static <T> Result<T> ok() {
        return restResult(null, SUCCESS, "操作成功");
    }

    public static <T> Result<T> ok(T data) {
        return restResult(data, SUCCESS, "操作成功");
    }

    public static <T> Result<T> ok(T data, String msg) {
        return restResult(data, SUCCESS, msg);
    }

    public static <T> Result<T> fail() {
        return restResult(null, FAIL, "操作失败");
    }

    public static <T> Result<T> fail(String msg) {
        return restResult(null, FAIL, msg);
    }

    public static <T> Result<T> fail(T data) {
        return restResult(data, FAIL, "操作失败");
    }

    public static <T> Result<T> fail(T data, String msg) {
        return restResult(data, FAIL, msg);
    }

    public static <T> Result<T> fail(int code, String msg) {
        return restResult(null, code, msg);
    }

    // ========== 响应对象校验 isError是否响应失败、isSuccess是否响应成功 ========== //

    public static <T> Boolean isError(Result<T> ret) {
        return !isSuccess(ret);
    }

    public static <T> Boolean isSuccess(Result<T> ret) {
        return Result.SUCCESS == ret.getCode();
    }

    // ============================= GET/SET方法 =============================//

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
